﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ChuanYe.Models;
using ChuanYe.Models.Model;
using ChuanYe.IDAL;
using System.IO;
using ChuanYe.Utils;

namespace ChuanYe.DAL
{
    public class DocumentInfosDAL:IDocumentInfosDAL
    {
        /// <summary>
        /// 获取全部部门
        /// </summary>
        /// <returns></returns>
        public List<Departments> DepartmentsIsSend()
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                return db.Departments.Where(m=>m.IsSend==true).OrderBy(o=>o.Sort).ToList();
            }
        }

        public List<Departments> DepartmentsManagerCode()
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                return db.Departments.Where(m =>!string.IsNullOrEmpty(m.ManagerCode)).OrderBy(o=>o.Sort).ToList();
            }
        }

        /// <summary>
        /// 发送公文
        /// </summary>
        /// <param name="DInfo">公文信息</param>
        /// <param name="DAttachs">附件信息</param>
        /// <param name="DSms">短信信息</param>
        /// <returns></returns>
        public int DocumentInfosCreate(DocumentInfos DInfo,List<DocumentAttachs> DAttachs, Sms_SendInfo DSms)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                db.DocumentInfos.Add(DInfo);
                int result = db.SaveChanges();
                if (DAttachs != new List<DocumentAttachs>())
                {
                    foreach (DocumentAttachs model in DAttachs)
                    {
                        model.DocumentID = DInfo.ID;
                        db.DocumentAttachs.Add(model);
                        db.SaveChanges();
                    }
                }
                if (DInfo.IsSMS == 1)
                {
                    Departments Department = db.Departments.FirstOrDefault(m => m.ID == DInfo.InceptDep);
                    //查询出所有大区下的用户，不包含在线值守
                    var users=db.UsersInfos.Where(p => p.Section == Department.ID && p.IsOfficial==true && p.IsManager !=true).ToList();
                    foreach (var item in users)
                    {
                        Sms_SendInfo smsInfo = new Sms_SendInfo();
                        smsInfo.IsAchieved = DSms.IsAchieved;
                        smsInfo.IsSafety = DSms.IsSafety;
                        smsInfo.SafetyCode = Guid.NewGuid().ToString();
                        smsInfo.SendDate = DateTime.Now;
                        smsInfo.Sender = DSms.Sender;
                        smsInfo.SenderCode = DSms.SenderCode;
                        smsInfo.SmsInfo = DSms.SmsInfo;
                        smsInfo.Receiver = item.UserName;
                        smsInfo.MobileCode = item.Phone;
                        db.Sms_SendInfo.Add(smsInfo);
                        db.SaveChanges();
                    }
                    //避免部门领导与用户表冲突
                    var existLeader = users.Where(p=>p.Phone ==Department.LeaderTel).FirstOrDefault();
                    if (existLeader == null)
                    {
                        DSms.Receiver = Department.Leader;
                        DSms.MobileCode = Department.LeaderTel;
                        db.Sms_SendInfo.Add(DSms);
                        db.SaveChanges();
                    }
                }
                return result;
            }
        }
        /// <summary>
        /// 已发送公文
        /// </summary>
        /// <param name="search">查询条件</param>
        /// <param name="Pager">分页信息</param>
        /// <returns></returns>
        public DocumentInfosSendResult DocumentInfosGetSend(DocumentInfosSendSearch search, GridPager Pager)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                var linq = db.DocumentInfos
                    .GroupJoin(
                    db.Departments,
                    A => A.InceptDep,
                    B => B.ID,
                    (A, B) => new DocumentInfosModel
                    {
                        Content = A.Content,
                        FileTitle = A.FileTitle,
                        DocumentType = A.DocumentType,
                        ID = A.ID,
                        InceptDate = A.InceptDate,
                        InceptDep = A.InceptDep,
                        InceptDepConvene = A.InceptDepConvene,
                        InceptDepName = B.FirstOrDefault(M => M.ID == A.InceptDep).DepName,
                        InceptPerson = A.InceptPerson,
                        InceptTel = A.InceptTel,
                        IsSMS = A.IsSMS,
                        IsView = A.IsView,
                        PublishCode = A.PublishCode,
                        PublishDate = A.PublishDate,
                        publishDep = A.publishDep,
                        PublishDepName = A.PublishDepName,
                        PublishPerson = A.PublishPerson,
                        Title = A.Title
                    }
                    )
                    .OrderByDescending(M => M.PublishDate)
                    .Where(
                    m => 
                    //m.publishDep == search.DepID &&
                    m.PublishDate >= search.stateTime &&
                    m.PublishDate <= search.endTime &&
                    (search.Title == "" 
                     || m.Title.Contains(search.Title) 
                     || m.InceptPerson.Contains(search.Title)
                     || m.PublishPerson.Contains(search.Title)
                     || m.InceptDepName.Contains(search.Title) 
                     )&&
                    (search.ToDepID == 0 || m.InceptDep == search.ToDepID) &&
                    (search.IsView == null || m.IsView == search.IsView)
                    );
                DocumentInfosSendResult result = new DocumentInfosSendResult();
                result.totalRows = linq.Count();
                result.DocumentInfosList= linq.Skip(Pager.rows * (Pager.page - 1)).Take(Pager.rows).ToList();
                return result;
            }
        }
        /// <summary>
        /// 市局公文查询
        /// </summary>
        /// <param name="search">查询条件</param>
        /// <param name="Pager">分页信息</param>
        /// <returns></returns>
        public DocumentInfosReceiveResult DocumentInfosReceive(DocumentInfosReceiveSearch search, GridPager Pager)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                var where = PredicateExtensionses.True<DocumentInfos>();
                where = where.And(p => p.PublishDate > search.stateTime);
                where = where.And(p => p.PublishDate < search.endTime);
                var linq = db.DocumentInfos
                    .Where(where)
                    .GroupBy(A=>new {A.Title,A.DocumentType,A.PublishPerson,A.PublishDate,A.IsSMS,
                           //A.IsOverTime,
                           //A.IsView
                    })
                    .Select(S=>new DocumentInfosModel
                    {
                        ID= S.FirstOrDefault().ID,
                        Title =S.Key.Title,
                        DocumentType =S.Key.DocumentType,
                        PublishPerson =S.Key.PublishPerson,
                        PublishDate =S.Key.PublishDate,
                        //IsView= S.Key.IsView,
                        IsSMS =S.Key.IsSMS,
                        //IsOverTime = S.Key.IsOverTime
                    });
                if (!string.IsNullOrEmpty(search.Title))
                {
                    linq = linq.Where(p => p.Title.Contains(search.Title) || p.PublishPerson.Contains(search.Title));
                }

                DocumentInfosReceiveResult result = new DocumentInfosReceiveResult();
                result.totalRows = linq.Count();
                result.DocumentInfosList = linq
                    .OrderByDescending(M => M.PublishDate)
                    .Skip(Pager.rows * (Pager.page - 1))
                    .Take(Pager.rows)
                    .ToList();
                return result;
            }
        }
        /// <summary>
        /// 获取公文查询公文详情
        /// </summary>
        /// <param name="model">查询条件</param>
        /// <returns></returns>
        public DocumentAllInfosModel DocumentInfosGetByBatch(DocumentInfosGetByBatchSearch model)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                DocumentAllInfosModel result = new DocumentAllInfosModel();
                DocumentInfos DF = db.DocumentInfos.FirstOrDefault(m => m.ID == model.ID);
                var linq = db.DocumentInfos.Where(m =>
                m.PublishDate == DF.PublishDate &&
                m.PublishPerson == DF.PublishPerson &&
                m.Title== DF.Title
                );
                result.DocumentInfo = DF;
                if (result.DocumentInfo != null)
                {
                    result.DocumentAttach = db.DocumentAttachs.Where(a => a.DocumentID == result.DocumentInfo.ID).ToList();
                    result.InceptDeps = linq.Select(a => a.InceptDepName).ToArray();
                }
                return result;
            }
        }
        /// <summary>
        /// 获取公文详情
        /// </summary>
        /// <param name="ID">公文ID</param>
        /// <returns></returns>
        public DocumentAllInfosModel DocumentInfosGetByID(int ID)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                DocumentAllInfosModel result = new DocumentAllInfosModel();
                result.DocumentInfo = db.DocumentInfos.FirstOrDefault(m => m.ID == ID);
                if (result.DocumentInfo != null)
                {
                    result.DocumentAttach = db.DocumentAttachs.Where(a => a.DocumentID == result.DocumentInfo.ID).ToList();
                }
                return result;
            }
        }
        /// <summary>
        /// 删除公文
        /// </summary>
        /// <param name="ID">公文ID</param>
        /// <returns></returns>
        public int DocumentInfosDelete(int ID)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                DocumentInfos model = db.DocumentInfos.FirstOrDefault(m => m.ID == ID);
                if (model != null)
                {
                    List<DocumentAttachs> List= db.DocumentAttachs.Where(m => m.DocumentID == model.ID).ToList();
                    foreach (DocumentAttachs DA in List)
                    {
                        string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, DA.FilePath);
                        File.Delete(filePath);
                    }
                    db.DocumentAttachs.RemoveRange(List);
                    db.SaveChanges();
                    db.DocumentInfos.Remove(model);
                }
                return db.SaveChanges();
            }
        }
        /// <summary>
        /// 删除附件
        /// </summary>
        /// <param name="ID">附件ID</param>
        /// <returns></returns>
        public int DocumentAttachsDelete(int ID)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                DocumentAttachs model = db.DocumentAttachs.FirstOrDefault(m => m.ID == ID);
                if (model != null)
                {
                    string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, model.FilePath);
                    File.Delete(filePath);
                    db.DocumentAttachs.Remove(model);
                }
                return db.SaveChanges();
            }
        }

        /// <summary>
        /// 修改公文接收是否超时状态
        /// </summary>
        /// <param name="Model"></param>
        /// <returns></returns>
        public string DocumentInfosIsOverTime(OverTimeModel Model)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                DocumentInfos result = db.DocumentInfos.FirstOrDefault(m => m.ID == Model.ID);
                if (result != null)
                {
                    TimeSpan Span = Convert.ToDateTime(Model.endTime).Subtract(Convert.ToDateTime(result.PublishDate));
                    double TotalMinutes = Span.TotalMinutes;
                    if (TotalMinutes > Model.OverTime)
                    {
                        result.IsOverTime = "-1";
                        db.SaveChanges();
                    }
                    //else
                    //{
                    //    result.IsOverTime = "0";
                    //    db.SaveChanges();
                    //}
                }
                return result.IsOverTime;
            }
        }

        /// <summary>
        /// 接收公文
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int DocumentInfosReceive(DocumentInfosModel model)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                DocumentInfos result = db.DocumentInfos.FirstOrDefault(m => m.ID == model.ID);
                if (result != null)
                {
                    result.InceptPerson = model.InceptPerson;
                    result.IsView = true;
                    result.InceptDate = model.InceptDate;
                }
                return db.SaveChanges();
            }
        }
        /// <summary>
        /// 区县公文接收
        /// </summary>
        /// <param name="search">查询条件</param>
        /// <param name="Pager">分页信息</param>
        /// <returns></returns>
        public DocumentInfosWaitReceiveResult DocumentInfosWaitReceive(DocumentInfosWaitReceiveSearch search, GridPager Pager)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                var linq = db.DocumentInfos
                    .Where(
                    m => m.InceptDep == search.DepID &&
                    m.PublishDate >= search.stateTime &&
                    m.PublishDate <= search.endTime &&
                    (search.Title == "" || m.Title.Contains(search.Title))&&
                    m.IsView==false
                    );
                DocumentInfosWaitReceiveResult result = new DocumentInfosWaitReceiveResult();
                result.totalRows = linq.Count();
                result.DocumentInfosList = linq
                    .OrderByDescending(M => M.PublishDate)
                    .Skip(Pager.rows * (Pager.page - 1))
                    .Take(Pager.rows)
                    .ToList();
                return result;
            }
        }
        /// <summary>
        /// 区县已收公文
        /// </summary>
        /// <param name="search">查询条件</param>
        /// <param name="Pager">分页信息</param>
        /// <returns></returns>
        public DocumentInfosReceivedResult DocumentInfosReceived(DocumentInfosReceivedSearch search, GridPager Pager)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                var linq = db.DocumentInfos
                    .Where(
                    m => m.InceptDep == search.DepID &&
                    m.PublishDate >= search.stateTime &&
                    m.PublishDate <= search.endTime &&
                    (search.Title == "" || m.Title.Contains(search.Title)) &&
                    m.IsView == true
                    );
                DocumentInfosReceivedResult result = new DocumentInfosReceivedResult();
                result.totalRows = linq.Count();
                result.DocumentInfosList = linq
                    .OrderByDescending(M => M.PublishDate)
                    .Skip(Pager.rows * (Pager.page - 1))
                    .Take(Pager.rows)
                    .ToList();
                return result;
            }
        }

        /// <summary>
        /// 获取未接收的公文
        /// </summary>
        /// <param name="depId"></param>
        /// <returns></returns>
        public int GetUnReadDocument(int depId)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                var linq = db.DocumentInfos.Where( m => m.InceptDep == depId &&m.IsView == false );
                return linq.Count();
            }
        }


        /// <summary>
        /// 查出超出20分钟的未接收的公文
        /// </summary>
        /// <param name="depId"></param>
        /// <returns></returns>
        public DocumentInfosReceivedResult GetUnReceivedDocument(int depId)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                //将当前时间减少20分钟
                DocumentInfosReceivedResult result = new DocumentInfosReceivedResult();
                var date20 = DateTime.Now.AddMinutes(-20);
                var data = db.DocumentInfos.Where(m => m.InceptDep == depId
                                                      && m.PublishDate < date20
                                                      && m.IsView == false).ToList();
                result.DocumentInfosList = data;
                result.totalRows = data.Count();
                return result;
            }
        }

    }
}
